package com.efounder.email.util;

import android.annotation.TargetApi;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.media.ThumbnailUtils;
import android.net.Uri;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;

import com.efounder.ospmobilelib.R;
import com.utilcode.util.UriUtils;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

public class FileUtil {

	public static Intent openFile(String filePath) {

		File file = new File(filePath);
		if (!file.exists())
			return null;
		/* 鍙栧緱鎵╁睍鍚� */
		String end = file
				.getName()
				.substring(file.getName().lastIndexOf(".") + 1,
						file.getName().length()).toLowerCase();
		/* 渚濇墿灞曞悕鐨勭被鍨嬪喅瀹歁imeType */
		if (end.equals("m4a") || end.equals("mp3") || end.equals("mid")
				|| end.equals("xmf") || end.equals("ogg") || end.equals("wav")) {
			return getAudioFileIntent(filePath);
		} else if (end.equals("3gp") || end.equals("mp4")) {
			return getAudioFileIntent(filePath);
		} else if (end.equals("jpg") || end.equals("gif") || end.equals("png")
				|| end.equals("jpeg") || end.equals("bmp")) {
			return getImageFileIntent(filePath);
		} else if (end.equals("apk")) {
			return getApkFileIntent(filePath);
		} else if (end.equals("ppt")) {
			return getPptFileIntent(filePath);
		} else if (end.equals("xls")) {
			return getExcelFileIntent(filePath);
		} else if (end.equals("doc")) {
			return getWordFileIntent(filePath);
		} else if (end.equals("pdf")) {
			return getPdfFileIntent(filePath);
		} else if (end.equals("chm")) {
			return getChmFileIntent(filePath);
		} else if (end.equals("txt")) {
			return getTextFileIntent(filePath, false);
		} else {
			return getAllIntent(filePath);
		}
	}

	// Android鑾峰彇涓�涓敤浜庢墦寮�APK鏂囦欢鐨刬ntent
	public static Intent getAllIntent(String param) {

		Intent intent = new Intent();
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
		intent.setAction(android.content.Intent.ACTION_VIEW);
		Uri uri = UriUtils.getUriForFile(new File(param));
		intent.setDataAndType(uri, "*/*");
		return intent;
	}

	// Android鑾峰彇涓�涓敤浜庢墦寮�APK鏂囦欢鐨刬ntent
	public static Intent getApkFileIntent(String param) {

		Intent intent = new Intent();
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
		intent.setAction(android.content.Intent.ACTION_VIEW);
		Uri uri = UriUtils.getUriForFile(new File(param));
		intent.setDataAndType(uri, "application/vnd.android.package-archive");
		return intent;
	}

	// Android鑾峰彇涓�涓敤浜庢墦寮�VIDEO鏂囦欢鐨刬ntent
	public static Intent getVideoFileIntent(String param) {

		Intent intent = new Intent("android.intent.action.VIEW");
		intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
		intent.putExtra("oneshot", 0);
		intent.putExtra("configchange", 0);
		Uri uri = UriUtils.getUriForFile(new File(param));
		intent.setDataAndType(uri, "video/*");
		return intent;
	}

	// Android鑾峰彇涓�涓敤浜庢墦寮�AUDIO鏂囦欢鐨刬ntent
	public static Intent getAudioFileIntent(String param) {

		Intent intent = new Intent("android.intent.action.VIEW");
		intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
		intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		intent.putExtra("oneshot", 0);
		intent.putExtra("configchange", 0);
		Uri uri = UriUtils.getUriForFile(new File(param));
		intent.setDataAndType(uri, "audio/*");
		return intent;
	}

	// Android鑾峰彇涓�涓敤浜庢墦寮�Html鏂囦欢鐨刬ntent
	public static Intent getHtmlFileIntent(String param) {

		Uri uri = Uri.parse(param).buildUpon()
				.encodedAuthority("com.android.htmlfileprovider")
				.scheme("content").encodedPath(param).build();
		Intent intent = new Intent("android.intent.action.VIEW");
		intent.setDataAndType(uri, "text/html");
		intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
		return intent;
	}

	// Android鑾峰彇涓�涓敤浜庢墦寮�鍥剧墖鏂囦欢鐨刬ntent
	public static Intent getImageFileIntent(String param) {

		Intent intent = new Intent("android.intent.action.VIEW");
		intent.addCategory("android.intent.category.DEFAULT");
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
		Uri uri = UriUtils.getUriForFile(new File(param));
		intent.setDataAndType(uri, "image/*");
		return intent;
	}

	// Android鑾峰彇涓�涓敤浜庢墦寮�PPT鏂囦欢鐨刬ntent
	public static Intent getPptFileIntent(String param) {

		Intent intent = new Intent("android.intent.action.VIEW");
		intent.addCategory("android.intent.category.DEFAULT");
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
		Uri uri = UriUtils.getUriForFile(new File(param));
		intent.setDataAndType(uri, "application/vnd.ms-powerpoint");
		return intent;
	}

	// Android鑾峰彇涓�涓敤浜庢墦寮�Excel鏂囦欢鐨刬ntent
	public static Intent getExcelFileIntent(String param) {

		Intent intent = new Intent("android.intent.action.VIEW");
		intent.addCategory("android.intent.category.DEFAULT");
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
		Uri uri = UriUtils.getUriForFile(new File(param));
		intent.setDataAndType(uri, "application/vnd.ms-excel");
		return intent;
	}

	// Android鑾峰彇涓�涓敤浜庢墦寮�Word鏂囦欢鐨刬ntent
	public static Intent getWordFileIntent(String param) {

		Intent intent = new Intent("android.intent.action.VIEW");
		intent.addCategory("android.intent.category.DEFAULT");
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
		Uri uri = UriUtils.getUriForFile(new File(param));
		intent.setDataAndType(uri, "application/msword");
		return intent;
	}

	// Android鑾峰彇涓�涓敤浜庢墦寮�CHM鏂囦欢鐨刬ntent
	public static Intent getChmFileIntent(String param) {

		Intent intent = new Intent("android.intent.action.VIEW");
		intent.addCategory("android.intent.category.DEFAULT");
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
		Uri uri = UriUtils.getUriForFile(new File(param));
		intent.setDataAndType(uri, "application/x-chm");
		return intent;
	}

	// Android鑾峰彇涓�涓敤浜庢墦寮�鏂囨湰鏂囦欢鐨刬ntent
	public static Intent getTextFileIntent(String param, boolean paramBoolean) {

		Intent intent = new Intent("android.intent.action.VIEW");
		intent.addCategory("android.intent.category.DEFAULT");
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
		if (paramBoolean) {
			Uri uri1 = Uri.parse(param);
			intent.setDataAndType(uri1, "text/plain");
		} else {
			Uri uri2 = UriUtils.getUriForFile(new File(param));
			intent.setDataAndType(uri2, "text/plain");
		}
		return intent;
	}

	// Android鑾峰彇涓�涓敤浜庢墦寮�PDF鏂囦欢鐨刬ntent
	public static Intent getPdfFileIntent(String param) {

		Intent intent = new Intent("android.intent.action.VIEW");
		intent.addCategory("android.intent.category.DEFAULT");
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
		Uri uri = UriUtils.getUriForFile(new File(param));
		intent.setDataAndType(uri, "application/pdf");
		return intent;
	}

	/**
	 *  寰楀埌鏂囦欢鐨勮矾寰�
	 *
	 * @param context
	 * @param uri
	 * @return
	 */
	public static String getFilePath(Context context, Uri uri) {

		if ("content".equalsIgnoreCase(uri.getScheme())) {
			String[] projection = { "_data" };
			Cursor cursor = null;

			try {
				cursor = context.getContentResolver().query(uri, projection,
						null, null, null);
				int column_index = cursor.getColumnIndexOrThrow("_data");
				if (cursor.moveToFirst()) {
					return cursor.getString(column_index);
				}
			} catch (Exception e) {
			}
		}

		else if ("file".equalsIgnoreCase(uri.getScheme())) {
			return uri.getPath();
		}

		return null;
	}

	/**
	 * 鏍规嵁鎸囧畾鐨勫浘鍍忚矾寰勫拰澶у皬鏉ヨ幏鍙栫缉鐣ュ浘 姝ゆ柟娉曟湁涓ょ偣濂藉锛� 1.
	 * 浣跨敤杈冨皬鐨勫唴瀛樼┖闂达紝绗竴娆¤幏鍙栫殑bitmap瀹為檯涓婁负null锛屽彧鏄负浜嗚鍙栧搴﹀拰楂樺害锛�
	 * 绗簩娆¤鍙栫殑bitmap鏄牴鎹瘮渚嬪帇缂╄繃鐨勫浘鍍忥紝绗笁娆¤鍙栫殑bitmap鏄墍瑕佺殑缂╃暐鍥俱�� 2.
	 * 缂╃暐鍥惧浜庡師鍥惧儚鏉ヨ娌℃湁鎷変几锛岃繖閲屼娇鐢ㄤ簡2.2鐗堟湰鐨勬柊宸ュ叿ThumbnailUtils锛屼娇 鐢ㄨ繖涓伐鍏风敓鎴愮殑鍥惧儚涓嶄細琚媺浼搞��
	 *
	 * @param imagePath
	 *            鍥惧儚鐨勮矾寰�
	 * @param width
	 *            鎸囧畾杈撳嚭鍥惧儚鐨勫搴�
	 * @param height
	 *            鎸囧畾杈撳嚭鍥惧儚鐨勯珮搴�
	 * @return 鐢熸垚鐨勭缉鐣ュ浘
	 */
	public static Bitmap getImageThumbnail(String imagePath, int width,
										   int height) {
		Bitmap bitmap = null;
		BitmapFactory.Options options = new BitmapFactory.Options();
		options.inJustDecodeBounds = true;
		// 鑾峰彇杩欎釜鍥剧墖鐨勫鍜岄珮锛屾敞鎰忔澶勭殑bitmap涓簄ull
		bitmap = BitmapFactory.decodeFile(imagePath, options);
		options.inJustDecodeBounds = false; // 璁句负 false
		// 璁＄畻缂╂斁姣�
		int h = options.outHeight;
		int w = options.outWidth;
		int beWidth = w / width;
		int beHeight = h / height;
		int be = 1;
		if (beWidth < beHeight) {
			be = beWidth;
		} else {
			be = beHeight;
		}
		if (be <= 0) {
			be = 1;
		}
		options.inSampleSize = be;
		// 閲嶆柊璇诲叆鍥剧墖锛岃鍙栫缉鏀惧悗鐨刡itmap锛屾敞鎰忚繖娆¤鎶妎ptions.inJustDecodeBounds 璁句负 false
		bitmap = BitmapFactory.decodeFile(imagePath, options);
		// 鍒╃敤ThumbnailUtils鏉ュ垱寤虹缉鐣ュ浘锛岃繖閲岃鎸囧畾瑕佺缉鏀惧摢涓狟itmap瀵硅薄
		bitmap = ThumbnailUtils.extractThumbnail(bitmap, width, height,
				ThumbnailUtils.OPTIONS_RECYCLE_INPUT);
		return bitmap;
	}

	/**
	 * 鑾峰彇瑙嗛鐨勭缉鐣ュ浘 鍏堥�氳繃ThumbnailUtils鏉ュ垱寤轰竴涓棰戠殑缂╃暐鍥撅紝鐒跺悗鍐嶅埄鐢═humbnailUtils鏉ョ敓鎴愭寚瀹氬ぇ灏忕殑缂╃暐鍥俱��
	 * 濡傛灉鎯宠鐨勭缉鐣ュ浘鐨勫鍜岄珮閮藉皬浜嶮ICRO_KIND锛屽垯绫诲瀷瑕佷娇鐢∕ICRO_KIND浣滀负kind鐨勫�硷紝杩欐牱浼氳妭鐪佸唴瀛樸��
	 *
	 * @param videoPath
	 *            瑙嗛鐨勮矾寰�
	 * @param width
	 *            鎸囧畾杈撳嚭瑙嗛缂╃暐鍥剧殑瀹藉害
	 * @param height
	 *            鎸囧畾杈撳嚭瑙嗛缂╃暐鍥剧殑楂樺害搴�
	 * @param kind
	 *            鍙傜収MediaStore.Images.Thumbnails绫讳腑鐨勫父閲廙INI_KIND鍜孧ICRO_KIND銆�
	 *            鍏朵腑锛孧INI_KIND: 512 x 384锛孧ICRO_KIND: 96 x 96
	 * @return 鎸囧畾澶у皬鐨勮棰戠缉鐣ュ浘
	 */
	public static Bitmap getVideoThumbnail(String videoPath, int width,
										   int height, int kind) {
		Bitmap bitmap = null;
		// 鑾峰彇瑙嗛鐨勭缉鐣ュ浘
		bitmap = ThumbnailUtils.createVideoThumbnail(videoPath, kind);
		System.out.println("w" + bitmap.getWidth());
		System.out.println("h" + bitmap.getHeight());
		bitmap = ThumbnailUtils.extractThumbnail(bitmap, width, height,
				ThumbnailUtils.OPTIONS_RECYCLE_INPUT);
		return bitmap;
	}




	/**
	 * 浠庢枃浠惰矾寰勪腑鑾峰彇鏂囦欢绫诲瀷骞惰幏鍙�  鏂囦欢绫诲瀷鐨勫浘鐗�
	 * @param context
	 * @param path
	 * @return
	 */
	public static Bitmap getImageFrompath(Context context, String path) {

		Bitmap bitmap = null;
		// 鏂囦欢绫诲瀷
		if (path !=null) {


			String fileType = path.substring(path.lastIndexOf(".") + 1);
			System.out.println(fileType);
			if (fileType.equalsIgnoreCase("jpg")
					|| fileType.equalsIgnoreCase("gif")
					|| fileType.equalsIgnoreCase("bmp")
					|| fileType.equalsIgnoreCase("png")
					|| fileType.equalsIgnoreCase("jpeg")) {
				//濡傛灉鍥剧墖璺緞鏄綉缁滀笂
				if (path.contains("http")) {
					bitmap = BitmapFactory.decodeResource(context.getResources(),
							R.drawable.attach_img);
				}else {
					//bitmap = getImageThumbnail(path, 200, 200);
					bitmap = BitmapFactory.decodeResource(context.getResources(),
							R.drawable.attach_img);
				}

			} else if (fileType.equalsIgnoreCase("doc")
					|| fileType.equalsIgnoreCase("docx")) {
				bitmap = BitmapFactory.decodeResource(context.getResources(),
						R.drawable.attach_word);
			} else if (fileType.equalsIgnoreCase("xls")
					|| fileType.equalsIgnoreCase("xlsx")) {
				bitmap = BitmapFactory.decodeResource(context.getResources(),
						R.drawable.attach_excel);
			} else if (fileType.equalsIgnoreCase("ppt")
					|| fileType.equalsIgnoreCase("pptx")) {
				bitmap = BitmapFactory.decodeResource(context.getResources(),
						R.drawable.attach_ppt);
			} else if (fileType.equalsIgnoreCase("pdf")) {
				bitmap = BitmapFactory.decodeResource(context.getResources(),
						R.drawable.attach_pdf);
			} else if (fileType.equalsIgnoreCase("txt")) {
				bitmap = BitmapFactory.decodeResource(context.getResources(),
						R.drawable.attach_txt);
			} else if (fileType.equalsIgnoreCase("rar")
					|| fileType.equalsIgnoreCase("zip")
					|| fileType.equalsIgnoreCase("7z")) {
				bitmap = BitmapFactory.decodeResource(context.getResources(),
						R.drawable.attach_rar);
			} else if (fileType.equalsIgnoreCase("mp3")
					|| fileType.equalsIgnoreCase("m4a")
					|| fileType.equalsIgnoreCase("mid")) {
				bitmap = BitmapFactory.decodeResource(context.getResources(),
						R.drawable.attach_music);
			} else {
				bitmap = BitmapFactory.decodeResource(context.getResources(),
						R.drawable.attach_unknown);
			}

			if (bitmap != null) {
				return toRoundCorner(bitmap, 10);
			} else {
				return BitmapFactory.decodeResource(context.getResources(),
						R.drawable.attach_unknown);
			}
		}

		return BitmapFactory.decodeResource(context.getResources(),
				R.drawable.attach_unknown);

	}

	/**
	 * 鑾峰彇鍦嗚浣嶅浘鐨勬柟娉�
	 *
	 * @param bitmap
	 *           瑕佽浆鍖栨垚鍦嗚鐨勪綅鍥�
	 * @param pixels
	 *            鍦嗚鐨勫害鏁帮紝鏁板�艰秺澶э紝鍦嗚瓒婂ぇ
	 * @return 澶勭悊鍚庣殑鍦嗚浣嶅浘
	 */
	public static Bitmap toRoundCorner(Bitmap bitmap, int pixels) {
		Bitmap output = Bitmap.createBitmap(bitmap.getWidth(),
				bitmap.getHeight(), Config.ARGB_8888);
		Canvas canvas = new Canvas(output);
		final int color = 0xff424242;
		final Paint paint = new Paint();
		final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
		final RectF rectF = new RectF(rect);
		final float roundPx = pixels;
		paint.setAntiAlias(true);
		canvas.drawARGB(0, 0, 0, 0);
		paint.setColor(color);
		canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
		paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
		canvas.drawBitmap(bitmap, rect, rect, paint);
		return output;
	}

	/**
	 * the traditional io way
	 * @param filename
	 * @return
	 * @throws IOException
	 */
	public static byte[] toByteArray(String filename) throws IOException{

		File f = new File(filename);
		if(!f.exists()){
			throw new FileNotFoundException(filename);
		}

		ByteArrayOutputStream bos = new ByteArrayOutputStream((int)f.length());
		BufferedInputStream in = null;
		try{
			in = new BufferedInputStream(new FileInputStream(f));
			int buf_size = 1024;
			byte[] buffer = new byte[buf_size];
			int len = 0;
			while(-1 != (len = in.read(buffer,0,buf_size))){
				bos.write(buffer,0,len);
			}
			return bos.toByteArray();
		}catch (IOException e) {
			e.printStackTrace();
			throw e;
		}finally{
			try{
				in.close();
			}catch (IOException e) {
				e.printStackTrace();
			}
			bos.close();
		}
	}


	/**
	 * 根据Uri获取文件的绝对路径，解决Android4.4以上版本Uri转换
	 *
	 * @param context
	 * @param fileUri
	 */
	@TargetApi(19)
	public static String getFileAbsolutePath(Context context, Uri fileUri) {
		if (context == null || fileUri == null)
			return null;
		if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT && DocumentsContract.isDocumentUri(context, fileUri)) {
			if (isExternalStorageDocument(fileUri)) {
				String docId = DocumentsContract.getDocumentId(fileUri);
				String[] split = docId.split(":");
				String type = split[0];
				if ("primary".equalsIgnoreCase(type)) {
					return Environment.getExternalStorageDirectory() + "/" + split[1];
				}
			} else if (isDownloadsDocument(fileUri)) {
				String id = DocumentsContract.getDocumentId(fileUri);
				Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
				return getDataColumn(context, contentUri, null, null);
			} else if (isMediaDocument(fileUri)) {
				String docId = DocumentsContract.getDocumentId(fileUri);
				String[] split = docId.split(":");
				String type = split[0];
				Uri contentUri = null;
				if ("image".equals(type)) {
					contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
				} else if ("video".equals(type)) {
					contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
				} else if ("audio".equals(type)) {
					contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
				}
				String selection = MediaStore.Images.Media._ID + "=?";
				String[] selectionArgs = new String[] { split[1] };
				return getDataColumn(context, contentUri, selection, selectionArgs);
			}
		} // MediaStore (and general)
		else if ("content".equalsIgnoreCase(fileUri.getScheme())) {
			// Return the remote address
			if (isGooglePhotosUri(fileUri))
				return fileUri.getLastPathSegment();
			return getDataColumn(context, fileUri, null, null);
		}
		// File
		else if ("file".equalsIgnoreCase(fileUri.getScheme())) {
			return fileUri.getPath();
		}
		return null;
	}

	public static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) {
		Cursor cursor = null;
		String[] projection = { MediaStore.Images.Media.DATA };
		try {
			cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null);
			if (cursor != null && cursor.moveToFirst()) {
				int index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
				return cursor.getString(index);
			}
		} finally {
			if (cursor != null)
				cursor.close();
		}
		return null;
	}

	/**
	 * @param uri
	 *            The Uri to check.
	 * @return Whether the Uri authority is ExternalStorageProvider.
	 */
	public static boolean isExternalStorageDocument(Uri uri) {
		return "com.android.externalstorage.documents".equals(uri.getAuthority());
	}

	/**
	 * @param uri
	 *            The Uri to check.
	 * @return Whether the Uri authority is DownloadsProvider.
	 */
	public static boolean isDownloadsDocument(Uri uri) {
		return "com.android.providers.downloads.documents".equals(uri.getAuthority());
	}

	/**
	 * @param uri
	 *            The Uri to check.
	 * @return Whether the Uri authority is MediaProvider.
	 */
	public static boolean isMediaDocument(Uri uri) {
		return "com.android.providers.media.documents".equals(uri.getAuthority());
	}

	/**
	 * @param uri
	 *            The Uri to check.
	 * @return Whether the Uri authority is Google Photos.
	 */
	public static boolean isGooglePhotosUri(Uri uri) {
		return "com.google.android.apps.photos.content".equals(uri.getAuthority());
	}
}
